package com.huaru.message.utile;

import com.huaru.message.Vo.DiskVO;
import com.huaru.message.Vo.UsageRateVO;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * 获取席位 内存 cpu  网上传输速度 工具类
 */
public class UsageRateUtils {

    private static final int SLEEP_TIME = 2*1000 ;

//    public static void main(String[] args) {
//        UsageRateVO usageRate = getUsageRate();
//        System.out.println(usageRate.getCpu());
//        System.out.println(usageRate.getMemory());
//        System.out.println(usageRate.getUpSpeed());
//        System.out.println(usageRate.getDownSpeed());
BigDecimal bg = new BigDecimal(1.2323);
    double v = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
//    }

    public static UsageRateVO getUsageRate(){
        //获取cpu使用率
        SystemInfo systemInfo = new SystemInfo();
        CentralProcessor processor = systemInfo.getHardware().getProcessor();
        long[] prevTicks = processor.getSystemCpuLoadTicks();
        long[] ticks = processor.getSystemCpuLoadTicks();
        long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.getIndex()];
        long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] - prevTicks[CentralProcessor.TickType.IRQ.getIndex()];
        long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()];
        long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()] - prevTicks[CentralProcessor.TickType.STEAL.getIndex()];
        long cSys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
        long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()];
        long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()];
        long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
        long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;

        //获取内存使用率
        GlobalMemory memory = systemInfo.getHardware().getMemory();
        long totalByte = memory.getTotal();
        long acaliableByte = memory.getAvailable();

        //获取网络传输速度
        Properties props = System.getProperties();
        String os = props.getProperty("os.name").toLowerCase();
        os = os.startsWith("win")?"windows":"linux";
        Map<String,String> result = new HashMap<>();
        Process pro = null;
        Runtime r = Runtime.getRuntime();
        BufferedReader input = null;
        double rxPercent = 0;
        double txPercent = 0;
        try {
            String command = "windows".equals(os)?"netstat -e":"ifconfig";
            pro = r.exec(command);
            input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            long result1[] = readInLine1(input, os);
            Thread.sleep(SLEEP_TIME);
            pro.destroy();
            input.close();
            pro = r.exec(command);
            input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            long result2[] = readInLine1(input, os);
            rxPercent = new BigDecimal((result2[0] - result1[0]) / (1024.0 * (SLEEP_TIME / 1000))).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            txPercent = new BigDecimal((result2[1]-result1[1])/(1024.0*(SLEEP_TIME / 1000))).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(input!=null){
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            Optional.ofNullable(pro).ifPresent(p->p.destroy());
        }
        //获取盘符使用情况
        File[] files = File.listRoots();
        List<DiskVO> diskVOS = new ArrayList<>();
        for (File file : files) {
            DiskVO diskVO = new DiskVO();
            diskVO.setName(file.getPath().substring(0,1));
            diskVO.setTotalSpace(file.getTotalSpace() / 1024 / 1024 / 1024);
            diskVO.setNoUsedSpace(file.getFreeSpace()/ 1024 / 1024 / 1024);
            diskVO.setUsedSpace((file.getTotalSpace() / 1024 / 1024 / 1024)- (file.getFreeSpace()/ 1024 / 1024 / 1024));
            diskVOS.add(diskVO);
        }
        UsageRateVO usageRateVO = new UsageRateVO();
        usageRateVO.setCpu( new BigDecimal(1.0 - (idle * 1.0 / totalCpu)).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
        usageRateVO.setMemory(new BigDecimal((totalByte - acaliableByte) * 1.0 / totalByte).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
        usageRateVO.setUpSpeed(rxPercent);
        usageRateVO.setDownSpeed(txPercent);
        usageRateVO.setDiskVOS(diskVOS);
        return  usageRateVO;
    }


    private static long[] readInLine1(BufferedReader input, String osType) {
        long arr[] = new long[2];
        StringTokenizer tokenStat = null;
        try {
            if (osType.equals("linux")) { // 获取linux环境下的网口上下行速率
                long rx=0,tx = 0;
                String line = null;
                //RX packets:4171603 errors:0 dropped:0 overruns:0 frame:0
                //TX packets:4171603 errors:0 dropped:0 overruns:0 carrier:0
                while((line=input.readLine())!=null){
                    if(line.indexOf("RX packets")>=0){
                        rx+=Long.parseLong(line.substring(line.indexOf("RX packets")+11,line.indexOf(" ",line.indexOf("RX packets")+11)));
                    }else if(line.indexOf("TX packets")>=0){
                        tx+=Long.parseLong(line.substring(line.indexOf("TX packets")+11,line.indexOf(" ",line.indexOf("TX packets")+11)));
                    }
                }
                arr[0]=rx;
                arr[1]=tx;
            } else { // 获取windows环境下的网口上下行速率
                input.readLine();
                input.readLine();
                input.readLine();
                input.readLine();
                tokenStat = new StringTokenizer(input.readLine());
                tokenStat.nextToken();
                arr[0] = Long.parseLong(tokenStat.nextToken());
                arr[1] = Long.parseLong(tokenStat.nextToken());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return arr;
    }

    /**
     * 格式化浮点数(float 和 double)，保留两位小数
     * @param obj
     * @return
     */

    private static String formatNumber(Object obj) {
        String result = "";

        if (obj.getClass().getSimpleName().equals("Float")) {
            result = new Formatter().format("%.2f", (float) obj).toString();

        } else if (obj.getClass().getSimpleName().equals("Double")) {
            result = new Formatter().format("%.2f", (double) obj).toString();

        }

        return result;

    }

    /**
     * 获取网口上下行速率
     * @param input
     */

    public static String[] readInLine(BufferedReader input, String osType) {
        String rxResult = "";

        String txResult = "";

        StringTokenizer tokenStat = null;

        try {
            if (osType.equals("linux")) { // 获取linux环境下的网口上下行速率

                String result[] = input.readLine().split(" ");

                int j = 0, k = 0;

                for (int i = 0; i < result.length; i++) {
                    if (result[i].indexOf("RX") != -1) {
                        j++;

                        if (j == 2) {
                            rxResult = result[i + 1].split(":")[1];

                        }

                    }

                    if (result[i].indexOf("TX") != -1) {
                        k++;

                        if (k == 2) {
                            txResult = result[i + 1].split(":")[1];

                            break;

                        }

                    }

                }

            } else { // 获取windows环境下的网口上下行速率

                input.readLine();

                input.readLine();

                input.readLine();

                input.readLine();

                tokenStat = new StringTokenizer(input.readLine());

                tokenStat.nextToken();

                rxResult = tokenStat.nextToken();

                txResult = tokenStat.nextToken();

            }

        } catch (Exception e) {


        }

        String arr[] = { rxResult, txResult };

        return arr;

    }
}
